var mongoose = require('mongoose');
//var $ = require('jquery');
var _ = require('lodash/core');
var Hospital = mongoose.model('Hospital');


function trimJSONStr(jStr){
  return JSON.stringify(JSON.parse(jStr));
}

module.exports.createHospital = function(hosData,cb){
  //console.log('hospital.dao:createHospital...',JSON.stringify(hosData,null,2));
  Hospital.create(hosData, function(err, hospital) {
    //console.log('create callback.');
    if (err) {
      console.log(err);
      //res.status(406).json(err);
      if(cb) cb(err,null);
      return;
    }
    console.log('hospital in dao:',JSON.stringify(hospital,null,2));
    if(cb) cb(null,hospital);
  });
  //console.log('createHospital over');
};

module.exports.updateHospital = function(hid,hosData,cb){
  //console.log('updateHospital-hosData:',JSON.stringify(hosData,null,2));
  //update hospital here:
  Hospital.findById(hid).exec(function(err, hospital) {
    if(err){
      console.error(err);
      if(cb) cb(err,null);
      return;
    }
    //console.log('hosData',JSON.stringify(hosData,null,2));
    var _hosData = _.assignIn(hosData,{updatedOn:Date.now()});
    //console.log('_hosData',JSON.stringify(_hosData,null,2));
    hospital.update(_hosData,function(err, updateRes) {
      if (err) {
        console.log(err);
        if(cb) cb(err,null);
      }
      if(cb) cb(null,updateRes);
    });
  });
};

module.exports.removeHospital = function(hid,cb){
  Hospital.findById(hid).select('status').exec(function(err, hospital) {
    if (err) {
      console.log(err);
      if(cb) cb(err,null);
      return;
    }
    hospital.status = 0;
    hospital.save(function(err,updatedHospital){
      if(err){
        console.log(err);
        if(cb) cb(err,null);
        return;
      }
      if(cb) cb(null,updatedHospital);
    });
  });
};

module.exports.getHospitalList = function(filter,limit,cb){
  Hospital.find(filter||{status:1}).limit(limit||20).sort('-createdOn').
    select('hcode name address gpsinfo introduction').
    exec(function(err, rows) {
      //console.log('in dao:',rows.length);
      if (err) {
        console.log(err);
        if(cb) cb(err,null);
        return;
      }
      if(cb) cb(null,rows);
    });
};

module.exports.getHospital = function(hid,cb){
  Hospital.findById(hid).exec(function(err, hospital) {
    if (err) {
      console.log(err);
      if(cb) cb(err,null);
      return;
    }
    if(cb) cb(null,hospital);
  });
};
